package com.example.demouser.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.example.demouser.bizservice.TestBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
public class TestController {
    Logger logger = LoggerFactory.getLogger(TestController.class);
    @Resource
    private TestBizService testBizService;

    @Resource
    private RedisTemplate redisTemplate;


    @GetMapping("/get")
    public Object test() throws Exception {
        return testBizService.test();
    }

    @GetMapping("/login")
    public Object login(HttpServletRequest request) {
        String token = UUID.fastUUID().toString();
        logger.info("token:" + token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "jin");
        jsonObject.put("address", "beijing");
        //request.getSession().setAttribute(token, jsonObject.toJSONString());
        redisTemplate.opsForValue().set(token, jsonObject.toJSONString());
        return "success";
    }

    /**
     * 网关重写了HttpServletRequest，一旦调用网关，session被置空 故不能用session去存数据 直接存redis
     *
     * @param request
     * @return
     */
    @GetMapping("/testSession")
    public Object testSession(HttpServletRequest request) {
        String token = request.getHeader("token");
        logger.info("token:" + token);
        //Object obj = request.getSession().getAttribute(token);
        //调用网关后session共享失效
        Object obj = redisTemplate.opsForValue().get(token);
        return obj;
    }
}
